from itsdangerous import TimedJSONWebSignatureSerializer as Serialzier
from django.conf import settings
from itsdangerous import BadData

from . import constants


def check_access_token(access_token_openid):
    """
    反解，反序列化access_token_openid
    :param access_token_openid:  密文
    :return:openid 明文
    """
    # 创建序列化器对象 序列化和反序列化的对象的参数必须是一模一样的
    s = Serialzier(settings.SECRET_KEY, constants.ACCESS_TOKEN_EXPIRES)

    # 反序列化openid密文变明文
    # openid = s.loads(access_token_openid)
    try:
        data = s.loads(access_token_openid)
    except BadData: # openid明文过期
        return None
    else:
        # 返回明文
        return data.get('openid')


def generate_access_token(openid):
    """
    签名/序列化openid

    :param openid: openid明文
    :return: token（openid密文）
    """
    # 创建序列化器对象
    # ('密钥：越复杂越安全','过期时间')
    s = Serialzier(settings.SECRET_KEY, constants.ACCESS_TOKEN_EXPIRES)
    # 准备带序列化的字典数据
    data = {'openid': openid}
    # 调用dumps方法进行序列化
    token = s.dumps(data)
    # 返回序列化之后的数据
    # return token
    return token.decode()